#pragma once

#include <iostream>
#include <queue>
#include <vector>
#include <memory>
#include <string>
#include "Log.hpp"
#include "Mutex.hpp"
#include "Pthread.hpp"
#include "Cond.hpp"
#include "Task.hpp"
namespace ThreadPoolModule
{
    using namespace ThreadMoudle;
    using namespace CondModule;
    using namespace LockModule;
    using namespace LogModule;

    using thread_t = std::shared_ptr<Thread>;
    const static int defaultnum = 5;

    void DefaultTest()
    {
        while (true)
        {
            LOG(LogLevel::DEBUG) << "test.....";
        }
    }
    template <class T>
    class ThreadPool
    {
    private:
        bool IsEmpty()
        {
            return _taskq.empty();
        }
        void HandlerTask(const std::string name)
        {
            LOG(LogLevel::INFO) << "线程: " << name << ", 进入HandlerTask的逻辑";
            while (true)
            {
                T t;
                // 1.拿任务
                {
                    LockGuard lockguard(_lock);
                    while (IsEmpty() && _isrunning)
                    {
                        _wait_num++;
                        _cond.Wait(_lock);
                        _wait_num--;
                    }
                    // 走到这里，有两种情况，1，任务队列不为空 2，线程池退出了
                    if (IsEmpty() && !_isrunning) // 如果任务队列为空，并且线程池退出了，就让线程自己退出循环
                        break;
                    t = _taskq.front();
                    _taskq.pop();

                } // 让锁出了这段区域后就释放，因为线程处理任务的时候不需要带着锁
                // 2.处理任务
                t(name); // 规定，未来所有的任务处理，全部都是必须提供()方法
            }
        }
        ThreadPool(const ThreadPool &) = delete;
        ThreadPool &operator=(const ThreadPool &) = delete;
        // 构造设为私有
        ThreadPool(int num = defaultnum) : _num(num), _wait_num(0), _isrunning(false)
        {
            for (int i = 0; i < num; i++)
            {
                _threads.push_back(std::make_shared<Thread>(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1)));
                LOG(LogLevel::INFO) << "构建线程" << _threads[i]->Name() << "对象... 成功";
            }
        }

    public:
        static ThreadPool<T> *GetInstance()
        {
            if (instance == NULL)//防止每次调用这个函数都要加锁，降低效率 
            {
                LockGuard lockguard(mtx);
                if (instance == NULL)
                {
                    LOG(LogLevel::INFO) << "单例首次执行，需要加载对象...";
                    instance = new ThreadPool<T>; // 懒汉
                }
                return instance;
            }
        }
        void Equeue(T &&in)
        {
            LockGuard lockguard(_lock);
            if (!_isrunning)
                return;
            _taskq.push(std::move(in));
            if (_wait_num > 0)
            {
                _cond.Notify();
            }
        }
        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (auto &thread_ptr : _threads)
            {
                thread_ptr->Start();
                LOG(LogLevel::INFO) << "启动线程" << thread_ptr->Name() << " ...成功";
            }
        }
        void Wait()
        {
            for (auto &thread_ptr : _threads)
            {
                thread_ptr->Join();
                LOG(LogLevel::INFO) << " 回收线程" << thread_ptr->Name() << " ...成功";
            }
        }
        void Stop()
        {
            LockGuard lockguard(_lock);
            if (_isrunning)
            {
                // 1,让线程子集退出（要唤醒）
                // 2,历史的任务被处理完了
                // 3,不能再入任务了
                _isrunning = false; // 状态设为不工作
                if (_wait_num > 0)
                    _cond.NotifyAll();
            }
        }
        ~ThreadPool()
        {
        }

    private:
        std::vector<thread_t> _threads;
        int _wait_num;
        int _num;             // 线程的个数
        std::queue<T> _taskq; // 任务队列,临界资源
        Mutex _lock;
        Cond _cond;
        bool _isrunning;

        static ThreadPool<T> *instance;
        static Mutex mtx; // 只用来保护单例
    };

    template <class T>
    ThreadPool<T> *ThreadPool<T>::instance = NULL;
    template <class T>
    Mutex ThreadPool<T>::mtx;
}